<template>
  <div class="products-container">
    <div class="page-header">
      <h2>产品管理</h2>
      <el-button type="primary" @click="handleAdd">新增产品</el-button>
    </div>
    
    <!-- Search Form -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.name" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.category" placeholder="请选择类型" clearable>
            <el-option label="电子产品" value="electronics"></el-option>
            <el-option label="服装" value="clothing"></el-option>
            <el-option label="食品" value="food"></el-option>
            <el-option label="家居" value="home"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- Table -->
    <el-card>
      <div slot="header" class="clearfix">
        <span>产品列表</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="productList"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="name"
          label="产品名称">
        </el-table-column>
        <el-table-column
          prop="category"
          label="类型">
          <template slot-scope="scope">
            <el-tag>
              {{ categoryMap[scope.row.category] || scope.row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格">
          <template slot-scope="scope">
            ¥ {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="stock"
          label="库存">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'on' ? 'success' : 'info'">
              {{ scope.row.status === 'on' ? '在售' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- Dialog for adding/editing products -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="productForm" :rules="rules" ref="productForm" label-width="80px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择类型">
            <el-option label="电子产品" value="electronics"></el-option>
            <el-option label="服装" value="clothing"></el-option>
            <el-option label="食品" value="food"></el-option>
            <el-option label="家居" value="home"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="productForm.description"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio label="on">在售</el-radio>
            <el-radio label="off">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportDataToCsv } from '@/utils/export'

export default {
  name: 'Products',
  data() {
    return {
      loading: false,
      exportLoading: false,
      productList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        name: '',
        category: ''
      },
      dialogVisible: false,
      dialogTitle: '新增产品',
      isEdit: false,
      productForm: {
        id: null,
        name: '',
        category: '',
        price: 0,
        stock: 0,
        description: '',
        status: 'on'
      },
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择产品类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' }
        ]
      },
      categoryMap: {
        'electronics': '电子产品',
        'clothing': '服装',
        'food': '食品',
        'home': '家居'
      }
    }
  },
  created() {
    this.fetchProducts()
  },
  methods: {
    // 获取产品列表
    fetchProducts() {
      this.loading = true
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockProducts = []
        const categories = ['electronics', 'clothing', 'food', 'home']
        
        for (let i = 1; i <= 100; i++) {
          const category = categories[Math.floor(Math.random() * categories.length)]
          mockProducts.push({
            id: i,
            name: `产品${i}`,
            category: category,
            price: Math.round(Math.random() * 1000 * 100) / 100,
            stock: Math.floor(Math.random() * 1000),
            description: `这是产品${i}的描述信息，用于详细说明产品的特点和用途。`,
            status: Math.random() > 0.2 ? 'on' : 'off'
          })
        }
        
        // 搜索过滤
        let filteredProducts = [...mockProducts]
        if (this.searchForm.name) {
          filteredProducts = filteredProducts.filter(product => product.name.includes(this.searchForm.name))
        }
        if (this.searchForm.category) {
          filteredProducts = filteredProducts.filter(product => product.category === this.searchForm.category)
        }
        
        // 分页
        this.total = filteredProducts.length
        const startIndex = (this.currentPage - 1) * this.pageSize
        this.productList = filteredProducts.slice(startIndex, startIndex + this.pageSize)
        
        this.loading = false
      }, 500)
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchProducts()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        category: ''
      }
      this.handleSearch()
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchProducts()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchProducts()
    },
    
    // 添加产品
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增产品'
      this.productForm = {
        id: null,
        name: '',
        category: '',
        price: 0,
        stock: 0,
        description: '',
        status: 'on'
      }
      this.dialogVisible = true
    },
    
    // 编辑产品
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑产品'
      this.productForm = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    
    // 删除产品
    handleDelete(row) {
      this.$confirm('确认删除该产品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.productList = this.productList.filter(product => product.id !== row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.productForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 编辑模式，找到并更新产品
            const index = this.productList.findIndex(product => product.id === this.productForm.id)
            if (index !== -1) {
              this.productList.splice(index, 1, this.productForm)
            }
            this.$message.success('编辑成功')
          } else {
            // 新增模式，生成ID并添加到列表
            const newProduct = { ...this.productForm, id: Date.now() }
            this.productList.unshift(newProduct)
            this.$message.success('添加成功')
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },

    // 导出CSV
    async exportData() {
      this.exportLoading = true
      try {
        // 获取所有产品数据（模拟）
        const allData = this.productList || []
        
        const columns = [
          { prop: 'id', label: 'ID' },
          { prop: 'name', label: '产品名称' },
          { prop: 'category', label: '类型', formatter: (row) => this.categoryMap[row.category] || row.category },
          { prop: 'price', label: '价格', formatter: (row) => '¥' + row.price.toFixed(2) },
          { prop: 'stock', label: '库存' },
          { prop: 'status', label: '状态', formatter: (row) => row.status === 'on' ? '在售' : '下架' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `产品管理_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
}
</script>

<style scoped>
.products-container {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 